import { sequelize } from '../../db';
import bcrypt from 'bcryptjs';
import fs from 'fs';
import { AuthFailed } from '../../../code/http-exception';
import { Model, DataTypes } from 'sequelize';
import path from 'path';
import { cwd } from 'node:process';
import Role from './role';
import { config } from "../../../config";

class User extends Model {
    declare id: number
    declare avatar: any
    declare password1: string
    declare nickname: string
    declare phone: string
    declare RoomNumberId: number
    declare AreaId: number
    declare BlockNumberId: number;
    declare label: string;
    declare url: string;
    declare img: string;
    declare upLevel: string;
    static async verifyEmailPassword(phone: string, plainPassword: string) {
        const user = await User.findOne({
            where: {
                phone
            }, include: Role
        })
        if (!user) {
            throw new AuthFailed('账号不存在')
        }
        const correct = bcrypt.compareSync(
            plainPassword, user.dataValues.password1 as string)
        if (!correct) {
            throw new AuthFailed('密码不正确')
        }
        return user
    }
}

User.init({
    phone: {
        type: DataTypes.STRING,
        unique: true
    },
    password1: {
        type: DataTypes.STRING,
        set(val: string) {
            const salt = bcrypt.genSaltSync(10)
            const psw = bcrypt.hashSync(val, salt)
            this.setDataValue('password1', psw)
        }
    },
    nickname: DataTypes.STRING,
    avatar: {
        type: DataTypes.STRING
    },
    fullUrl: {
        type: DataTypes.VIRTUAL,
        get() {
            return this.dataValues.avatar ? config.BASEURL + this.dataValues.avatar : ''
        },
        set(value) {
            throw new Error('不要尝试设置 `fullUrl` 的值!');
        }
    },
    RoomNumberId: DataTypes.INTEGER,
    RoomNumber_name: DataTypes.STRING,
    AreaId: DataTypes.INTEGER,
    Area_name: DataTypes.STRING,
    BlockNumberId: DataTypes.INTEGER,
    BlockNumber_name: DataTypes.STRING,
    location: DataTypes.GEOMETRY('POINT'),
    token: DataTypes.STRING,
    pageIndex: DataTypes.STRING
}, {
    hooks: {
        afterUpdate: (user, options) => {
            //修改头像时删除原有图片
            if (options.fields?.includes('avatar') && user.previous().avatar) {
                fs.unlink(cwd() + '/public/uploads/' + path.basename(user.previous().avatar), (err) => {
                    // console.log(err)
                })
            }
        }
    },
    sequelize,
    paranoid: true
});

export default User